<template>
  <page-wrap stay-still back hide-tab title="交付服务">
    <view class="summary">
      <view class="summary-header">
        <text class="title">服务名称：</text>
        <text class="value">简历优化</text>
      </view>
      <view class="summary-form-wrap">
        <u-form
          class="summary-form"
          label-position="top"
          ref="uForm"
          :model="form"
          :error-type="['message']"
        >
          <block v-for="(item, index) in formList" :key="index">
            <view
              class="form-item-wrap"
              v-if="!item.baseOn || form[item.baseOn.prop] == item.baseOn.value"
              @click.capture="handleSelect(item, index)"
            >
              <u-form-item
                :class="{ pick: item.comp }"
                :label="item.label"
                :prop="item.prop"
              >
                <u-input
                  class="form-input"
                  v-model="form[item.prop]"
                  :disabled="!!item.comp"
                  :type="item.type"
                  :placeholder="item.inputPlaceholder"
                  :clearable="false"
                  @blur="handleSaveItem(item)"
                />
                <!-- 下拉选择 -->
                <u-select
                  class="form-select"
                  v-model="item.show"
                  :list="item.data"
                  v-if="item.comp === 'select'"
                  @confirm="handleConfirm($event, item)"
                ></u-select>
              </u-form-item>
            </view>
          </block>
        </u-form>
      </view>
      <view class="operate-bar">
        <u-button
          class="save-btn"
          type="primary"
          shape="circle"
          :loading="loading"
          @click="handleSave"
          >保存</u-button
        >
        <u-button
          class="save-btn"
          type="default"
          shape="circle"
          :loading="publishLoading"
          @click="handlePublish"
          >发布</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import { uploadAction, uploadBaseUrl, viewServiceSummary } from '@/api/index';
import { editServiceSummary, pubServiceSummary } from '@/api/modules/career';
export default {
  components: {},
  data() {
    return {
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      userInfo: {},
      form: {
        username: '',
        userSex: '',
        userAge: '',
        questionType: '',
        optimization: '',
        optimizedResume: {}
      },
      formList: [
        {
          label: '用户姓名',
          prop: 'username',
          inputPlaceholder: '请输入用户姓名',
          type: 'text',
          dataType: 17
        },
        {
          label: '用户年龄',
          prop: 'userAge',
          inputPlaceholder: '请输入用户年龄',
          type: 'text',
          dataType: 19
        },
        {
          label: '用户性别',
          prop: 'userSex',
          inputPlaceholder: '请选择用户性别',
          comp: 'select',
          dataType: 18,
          data: [
            {
              label: '男',
              value: '男'
            },
            {
              label: '女',
              value: '女'
            }
          ],
          show: false
        },
        {
          label: '优化概述',
          prop: 'optimization',
          inputPlaceholder: '请输入优化概述',
          type: 'textarea',
          dataType: 5
        },
        {
          label: '交付简历',
          prop: 'optimizedResume',
          inputPlaceholder: '请上传交付简历',
          comp: 'select',
          upload: true,
          dataType: 4
        }
      ],
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['change', 'blur']
          }
        ],
        userSex: [
          {
            required: true,
            message: '请输入用户姓名',
            trigger: ['change', 'blur']
          }
        ],
        userAge: [
          {
            required: true,
            message: '请输用户年龄',
            trigger: ['change', 'blur']
          }
        ],
        optimization: [
          {
            required: true,
            message: '请输入优化概述',
            trigger: ['change', 'blur']
          }
        ],
        optimizedResume: [
          {
            required: true,
            message: '请输入解决方案',
            trigger: ['change', 'blur']
          }
        ]
      },
      loading: false,
      publishLoading: false,
      isUploaded: false,
      resumeList: [],
      serviceId: '',
      serviceRecordId: '',
      keyIdMap: new Map()
    };
  },
  watch: {
    userInfo: {
      handler(val) {
        this.form = {
          username: val.username,
          userSex: val.userSex,
          userAge: val.userAge,
          optimization: val.optimization,
          optimizedResume: val.optimizedResume
        };
      },
      immediate: true
    }
  },
  created() {},
  onLoad(opt) {
    this.serviceId = opt.serviceId || '';
    this.serviceRecordId = opt.serviceRecordId || '';
  },
  onShow() {},
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    handleSaveItem(item) {
      if (!this.form[item.prop] && !this.serviceId) {
        // 没有请求过又不是编辑，就return
        return;
      }
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId,
        dataType: item.dataType,
        content: this.form[item.prop]
      };
      this.editServiceSummaryFn(params);
    },
    editServiceSummaryFn(params) {
      editServiceSummary(params).then((res) => {
        if (res.code !== 200) {
          uni.showToast({ icon: 'none', title: res.status_desc });
        } else {
          if (!this.keyIdMap.get(res.data)) {
            // 编辑过后如果没有主键id的话就保存起来
            this.keyIdMap.set(params.dataType, res.data);
          }
          // uni.showToast({ icon: "none", title: "已保存当前更改" });
        }
      });
    },
    viewServiceSummaryFn() {
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId
      };
      viewServiceSummary(params).then((res) => {
        if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
          res.data.forEach((item) => {
            this.keyIdMap.set(item.dataType, item.id); // 保存每一项的主键id，用作编辑
            if (item.dataType == 17) {
              this.form.username = item.content;
            }
            if (item.dataType == 18) {
              this.form.userSex = item.userSex;
            }
            if (item.dataType == 19) {
              this.form.userAge = item.userAge;
            }
            if (item.dataType == 4) {
              this.form.optimizedResume = item.content;
            }
            if (item.dataType == 5) {
              this.form.optimization = item.content;
            }
          });
        }
      });
    },
    handlePublish() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            serviceRecordId: this.serviceRecordId,
            serviceId: this.serviceId
          };
          pubServiceSummary(params).then((res) => {
            if (res.code == 200) {
              uni.showToast({ icon: 'none', title: '发布成功！' });
            }
          });
        } else {
          uni.showToast({ icon: 'none', title: '请完善信息后再发布！' });
        }
      });
    },
    handleSave() {
      uni.navigateBack();
    },
    // 选择本地文件
    handleUpload() {
      // #ifdef H5
      let uploadApi = uni.chooseFile;
      // #endif
      // #ifdef MP-WEIXIN
      let uploadApi = wx.chooseMessageFile;
      // #endif
      const TYPE = ['.doc', '.docx', '.png', '.jpg', '.jepg', '.png', '.pdf'];
      uploadApi({
        count: 1, //默认100
        extension: TYPE,
        success: (res) => {
          let tempFilePaths = res.tempFiles;
          let fileExt = '.' + tempFilePaths[0].name.replace(/.+\./, '');
          if (TYPE.indexOf(fileExt) < 0) {
            return uni.showToast({
              icon: 'none',
              title: '文件类型错误'
            });
          }
          if (tempFilePaths[0].size / (1024 * 1024) > 10) {
            return uni.showToast({
              icon: 'none',
              title: '文件大小不能超过10M'
            });
          }
          uni.showLoading({
            title: '正在上传'
          });
          uni.uploadFile({
            url: uploadAction,
            filePath: tempFilePaths[0].path,
            name: 'file',
            success: (uploadRes) => {
              console.log(
                '🚀 ~ file: AttachmentUpload.vue:169 ~ handleUpload ~ uploadRes:',
                uploadRes
              );
              uni.showToast({
                icon: 'none',
                title: '上传成功'
              });
              let name = tempFilePaths[0].name;
              if (name.length > 10) {
                name = name.slice(0, 10) + '...';
              }
              let info = {
                resume: uploadBaseUrl + uploadRes.data,
                resumeName: tempFilePaths[0].name,
                resumeSimpleName: name
              };
              this.form.optimizedResume = info.resumeName;
              this.resumeList = info;
              this.isUploaded = true;
            }
          });
        }
      });
    },
    handleSelect(item) {
      if (item.upload) {
        this.handleUpload();
        return;
      }
      if (item.comp) {
        this.$set(item, 'show', true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, item.prop, time);
      }
      setTimeout(() => {
        this.$refs.uForm.validate();
        const params = {
          serviceRecordId: this.serviceRecordId,
          serviceId: this.serviceId,
          dataType: item.dataType,
          content: this.form[item.prop]
        };
        this.editServiceSummaryFn(params);
      }, 0);
    }
  }
};
</script>

<style lang="scss" scoped>
.summary {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 32rpx 32rpx 36rpx;
  box-sizing: border-box;
  position: relative;
  &-header {
    font-size: 32rpx;
    padding: 0 0 24rpx 32rpx;
    color: #333;
    font-weight: 600;
    .title {
      margin-right: 12rpx;
      color: #666;
    }
    .value {
      color: #555;
    }
  }
  .summary-form-wrap {
    flex-grow: 1;
    background: #fff;
    padding-top: 32rpx;
    border-radius: 16rpx;
    ::v-deep .u-form {
      padding: 0 32rpx;
      background: $uni-bg-color;
      border-radius: 24rpx;
      .u-form-item {
        .btn-group {
          padding: 0 24rpx;
          line-height: 102rpx;
          .cancel,
          .confirm {
            padding: 0 16rpx;
          }
        }
      }
    }
  }
  .operate-bar {
    display: flex;
    justify-content: space-evenly;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .save-btn {
      flex-shrink: 0;
      margin: 82rpx 0 4rpx;
      width: 40%;
    }
  }
}
::v-deep .u-input__textarea {
  min-height: 80rpx !important;
}
::v-deep .u-input input {
  font-size: 28rpx !important;
}
::v-deep .u-btn--default {
  color: #fff !important;
  border-color: #c0c4cc;
  background-color: #c0c4cc !important;
}
</style>
